﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using MMessaging.Address;
using MMessaging.MessagingEx.Common;
using MMessaging.MessagingEx.Services;
using MMessaging.Test.Fahrstuhl.Engine;
using MMessaging.WPF;
using TUtils.Extensions;

namespace MMessaging.Test.Fahrstuhl.ViewModels
{
	public partial class ElevatorViewModel
	{
		partial void OnConstructed()
		{
			SetCabinsPosition(floorNo: 0, up: false, progress: 0);
		}

		private void SetCabinsPosition(int floorNo, bool up, int progress)
		{
			int height = 200;
			if (up)
				progress *= -1;
			int top = 4 + (height - floorNo * height / 2 + progress * height / 2 / 100);
			ElevatorMargin = new Thickness(55, top, 0, 0);
		}

		/// <summary>
		/// running on WPF thread
		/// </summary>
		protected override void OnMessage(MAddressMessageBase message)
		{
			base.OnMessage(message);
			var msgElevatorStatus = message as ElevatorStatusMessage;
			if (msgElevatorStatus != null)
			{
				SetCabinsPosition(
					floorNo:(int)msgElevatorStatus.RecentFloor,
					up:msgElevatorStatus.Direction == MovementState.Up,
					progress:msgElevatorStatus.Progress);
			}
		}

		public void SetNewButtonState(ButtonStateBase newButtonState)
		{
			EngineAdapter.PostMessage(
				new ButtonStatusMessage(
					receiver:ElevatorEngine.ElevatorEngine.Instance.ServiceAddress,
					sender: EngineAdapter.ClientAddress,
					sendTime:DateTime.UtcNow,
					buttonState:newButtonState));
		}
	}
}
